<template>
  <a-modal
    :destroy-on-close="true"
    :mask-closable="false"
    :visible="visible"
    :title="title"
    :confirm-loading="loading"
    :width="'80%'"
    @cancel="handleClose"
    @ok="handleSubmit"
  >
    <a-form ref="formRef" :model="formData" :rules="formRules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-tabs v-model:activeKey="activeKey" size="small">
        <a-tab-pane :key="1" tab="基本信息">
          <a-row>
            <a-col :span="12">
              <a-form-item label="表名称" name="tableName">
                <a-input v-model:value="formData.tableName" placeholder="请输入表名称" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="表短名称" name="tableShortName">
                <a-input v-model:value="formData.tableShortName" placeholder="表短名称" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="表描述" name="tableComment">
                <a-input v-model:value="formData.tableComment" placeholder="请输入表描述" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="实体类名称" name="className">
                <a-input v-model:value="formData.className" placeholder="请输入实体类名称" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="作者" name="functionAuthor">
                <a-input v-model:value="formData.functionAuthor" placeholder="请输入作者" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="版本" name="functionVersion">
                <a-input v-model:value="formData.functionVersion" placeholder="请输入版本" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="备注" name="remark">
                <a-textarea v-model:value="formData.remark" placeholder="请输入备注" :rows="4" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-tab-pane>
        <a-tab-pane :key="2" tab="字段信息">
          <a-table
            size="small"
            :loading="loading"
            :columns="tableColumns"
            :data-source="tableDataSource"
            :pagination="false"
            row-key="columnId"
          >
            <template #bodyCell="{ index, column }">
              <template v-if="column.key === 'serialId'">
                {{ index + 1 }}
              </template>

              <template v-else-if="column.key === 'columnComment'">
                <a-input v-model:value="tableDataSource[index]['columnComment']"></a-input>
              </template>

              <template v-else-if="column.key === 'javaType'">
                <a-select v-model:value="tableDataSource[index]['javaType']">
                  <a-select-option value="Long">Long</a-select-option>
                  <a-select-option value="String">String</a-select-option>
                  <a-select-option value="Integer">Integer</a-select-option>
                  <a-select-option value="Double">Double</a-select-option>
                  <a-select-option value="BigDecimal">BigDecimal</a-select-option>
                  <a-select-option value="Date">Date</a-select-option>
                </a-select>
              </template>

              <template v-else-if="column.key === 'javaField'">
                <a-input v-model:value="tableDataSource[index]['javaField']"></a-input>
              </template>

              <template v-else-if="column.key === 'isInsert'">
                <a-checkbox v-model:checked="tableDataSource[index]['isInsert']" />
              </template>

              <template v-else-if="column.key === 'isEdit'">
                <a-checkbox v-model:checked="tableDataSource[index]['isEdit']" />
              </template>

              <template v-else-if="column.key === 'isList'">
                <a-checkbox v-model:checked="tableDataSource[index]['isList']" />
              </template>

              <template v-else-if="column.key === 'isQuery'">
                <a-checkbox v-model:checked="tableDataSource[index]['isQuery']" />
              </template>

              <template v-else-if="column.key === 'queryType'">
                <a-select v-model:value="tableDataSource[index]['queryType']">
                  <a-select-option value="EQ">=</a-select-option>
                  <a-select-option value="NE">!=</a-select-option>
                  <a-select-option value="GT">&gt;</a-select-option>
                  <a-select-option value="GTE">&gt;=</a-select-option>
                  <a-select-option value="LT">&lt;</a-select-option>
                  <a-select-option value="LET">&lt;=</a-select-option>
                  <a-select-option value="LIKE">LIKE</a-select-option>
                  <a-select-option value="BETWEEN">BETWEEN</a-select-option>
                </a-select>
              </template>

              <template v-else-if="column.key === 'isRequired'">
                <a-checkbox v-model:checked="tableDataSource[index]['isRequired']" />
              </template>

              <template v-else-if="column.key === 'htmlType'">
                <a-select v-model:value="tableDataSource[index]['htmlType']">
                  <a-select-option value="input">文本框</a-select-option>
                  <a-select-option value="textarea">文本域</a-select-option>
                  <a-select-option value="select">下拉框</a-select-option>
                  <a-select-option value="radio">单选框</a-select-option>
                  <a-select-option value="checkbox">复选框</a-select-option>
                  <a-select-option value="datetime">日期控件</a-select-option>
                  <a-select-option value="imageUpload">图片上传</a-select-option>
                  <a-select-option value="fileUpload">文件上传</a-select-option>
                  <a-select-option value="editor">富文本控件</a-select-option>
                </a-select>
              </template>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane :key="3" tab="生成信息">
          <a-row>
            <a-col :span="12">
              <a-form-item label="生成模板" name="tplCategory">
                <a-select v-model:value="formData.tplCategory" @change="handleTplCategoryChange">
                  <a-select-option value="crud">单表（增删改查）</a-select-option>
                  <a-select-option value="tree">树表（增删改查）</a-select-option>
                  <a-select-option value="sub">主子表（增删改查）</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="生成功能名" name="functionName" help="用作类描述，例如 用户">
                <a-input v-model:value="formData.functionName" placeholder="生成功能名" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="生成包路径" name="packageName" help="生成在哪个java包下，例如 com.bytesdream.emer">
                <a-input v-model:value="formData.packageName" placeholder="" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="生成业务名" name="businessName" help="可理解为功能英文名，例如 system">
                <a-input v-model:value="formData.businessName" placeholder="生成业务名" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="上级菜单" name="parentMenuId" help="分配到指定菜单下，例如 系统管理">
                <a-tree-select
                  v-model:value="formData.parentMenuId"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="menuOptions"
                  placeholder="请选择上级菜单"
                  tree-default-expand-all
                  allow-clear
                >
                </a-tree-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-show="formData.tplCategory === 'tree'">
            <a-divider>其他信息</a-divider>
            <a-col :span="12">
              <a-form-item label="树编ID字段" name="treeId" help="树显示的ID字段名， 如：dept_id">
                <a-select v-model:value="formData.treeId" placeholder="请选择" allow-clear>
                  <a-select-option v-for="(column, index) in tableDataSource" :key="index" :value="column.columnName">{{
                    column.columnName + "：" + column.columnComment
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="树父ID字段" name="treeParentId" help="树显示的父编码字段名， 如：parent_Id">
                <a-select v-model:value="formData.treeParentId" placeholder="请选择" allow-clear>
                  <a-select-option v-for="(column, index) in tableDataSource" :key="index" :value="column.columnName">{{
                    column.columnName + "：" + column.columnComment
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="树名称字段" name="treeName" help="树节点的显示名称字段名， 如：dept_name">
                <a-select v-model:value="formData.treeName" placeholder="请选择" allow-clear>
                  <a-select-option v-for="(column, index) in tableDataSource" :key="index" :value="column.columnName">{{
                    column.columnName + "：" + column.columnComment
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="树排序字段" name="treeSort" help="树节点的排序字段， 如：sort">
                <a-select v-model:value="formData.treeSort" placeholder="请选择" allow-clear>
                  <a-select-option v-for="(column, index) in tableDataSource" :key="index" :value="column.columnName">{{
                    column.columnName + "：" + column.columnComment
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-show="formData.tplCategory === 'sub'">
            <a-divider>关联信息</a-divider>
            <a-col :span="12">
              <a-form-item label="关联子表的表名" name="subTableName" help="关联子表的表名， 如：sys_user">
                <a-select
                  v-model:value="formData.subTableName"
                  placeholder="请选择"
                  allow-clear
                  @change="handleSubTableNameChange"
                >
                  <a-select-option v-for="(table, index) in tables" :key="index" :value="table.tableName">{{
                    table.tableName + "：" + table.tableComment
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="子表关联的外键名" name="subTableFkName" help="子表关联的外键名， 如：user_id">
                <a-select v-model:value="formData.subTableFkName" placeholder="请选择" allow-clear>
                  <a-select-option v-for="(column, index) in subColumns" :key="index" :value="column.columnName">{{
                    column.columnName + "：" + column.columnComment
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-tab-pane>
      </a-tabs>
    </a-form>
  </a-modal>
</template>

<script name="ToolGenEdit" lang="ts" setup>
import { getGenTable, updateGenTable } from "@/api/tool/gen";
import { getTree } from "@/api/system/menu";
import { formatTreeSelect } from "@/utils/format";

const emit = defineEmits(["reload"]);

const visible = ref(false);
const title = ref("修改生成配置");
const loading = ref(false);
const activeKey = ref(1);

const tables = ref<any>([]);
const subColumns = ref<any>([]);
const menuOptions = ref<any>([]);

const tableColumns = ref<TableColumn[]>([
  {
    key: "serialId",
    dataIndex: "serialId",
    title: "序号"
  },
  {
    key: "columnName",
    dataIndex: "columnName",
    title: "字段列名"
  },
  {
    key: "columnComment",
    dataIndex: "columnComment",
    title: "字段描述"
  },
  {
    key: "columnType",
    dataIndex: "columnType",
    title: "物理类型"
  },
  {
    key: "javaType",
    dataIndex: "javaType",
    title: "Java类型"
  },
  {
    key: "javaField",
    dataIndex: "javaField",
    title: "java属性"
  },
  {
    key: "isInsert",
    dataIndex: "isInsert",
    title: "插入"
  },
  {
    key: "isEdit",
    dataIndex: "isEdit",
    title: "编辑"
  },
  {
    key: "isList",
    dataIndex: "isList",
    title: "列表"
  },
  {
    key: "isQuery",
    dataIndex: "isQuery",
    title: "查询"
  },
  {
    key: "queryType",
    dataIndex: "queryType",
    title: "查询方式"
  },
  {
    key: "isRequired",
    dataIndex: "isRequired",
    title: "必填"
  },
  {
    key: "htmlType",
    dataIndex: "htmlType",
    title: "显示类型"
  }
]);
const tableDataSource = ref([]);

const formRef = ref();
const formData = reactive<any>({
  tableId: 0,
  tableName: ""
});
const formRules = reactive({
  tableName: [{ required: true, message: "请输入表名称", trigger: "blur" }],
  tableShortName: [{ required: true, message: "请输入表短名称", trigger: "blur" }],
  tableComment: [{ required: true, message: "请输入表描述", trigger: "blur" }],
  className: [{ required: true, message: "请输入实体类名称", trigger: "blur" }],
  functionAuthor: [{ required: true, message: "请输入作者", trigger: "blur" }],
  functionVersion: [{ required: true, message: "请输入版本", trigger: "blur" }],
  tplCategory: [{ required: true, message: "请选择生成模板", trigger: "blur" }],
  packageName: [{ required: true, message: "请输入生成包路径", trigger: "blur" }],
  moduleName: [{ required: true, message: "请输入生成模块名", trigger: "blur" }],
  businessName: [{ required: true, message: "请输入生成业务名", trigger: "blur" }],
  functionName: [{ required: true, message: "请输入生成功能名", trigger: "blur" }]
});

const handleTplCategoryChange = (value: string) => {
  if (value !== "sub") {
    formData.subTableName = "";
    formData.subTableFkName = "";
  }
  if (value != "tree") {
    formData.treeId = "";
    formData.treeParentId = "";
    formData.treeName = "";
    formData.treeSort = "";
  }
};

const handleSubTableNameChange = (value: any) => {
  formData.subTableFkName = undefined;
  for (const item in tables.value) {
    const name = tables.value[item].tableName;
    if (value === name) {
      subColumns.value = tables.value[item].columns;
      break;
    }
  }
};

const show = (id: number) => {
  visible.value = true;
  activeKey.value = 1;
  loading.value = true;
  getGenTable(id)
    .then(response => {
      loading.value = false;
      Object.assign(formData, response.data.info);
      tableDataSource.value = response.data.columns;
      tables.value = response.data.tables;
    })
    .catch(error => {
      loading.value = false;
      console.error(error);
    });

  getTree()
    .then(response => {
      menuOptions.value = formatTreeSelect(response.data);
      loading.value = false;
    })
    .catch(error => {
      loading.value = false;
      console.error(error);
    });
};

const handleClose = () => {
  visible.value = false;
};

const handleSubmit = () => {
  formRef.value
    .validate()
    .then(() => {
      loading.value = true;
      formData.columns = tableDataSource.value;
      updateGenTable(formData)
        .then(() => {
          antdMessage.success("编辑成功");
          emit("reload");
          handleClose();
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch(error => {
      console.log("error", error);
    });
};

defineExpose({ show });
</script>
